package lagou.homework.lagou_homework_rocketmq.task;

import lagou.homework.lagou_homework_rocketmq.entity.Seckill;
import lagou.homework.lagou_homework_rocketmq.repository.SeckillRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SeckillTask {
    @Autowired
    private SeckillRepository seckillRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每5秒一次，扫描秒杀加载到redis
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void loadSeckill(){
        /**
         * 从数据库加载开始秒杀到redis
         */
        List<Seckill> seckills = seckillRepository.loadSeckillList();
        /**
         * 循环
         */
        for(Seckill seckill:seckills){
            /**
             * 判断状态是已开始，不处理
             */
            if(seckill.getStatus() != 0){
                continue;
            }
            /**
             * 根据秒杀数量，生成队列，压入redis
             */
            log.info("加载seckillId={}的数据{}个到redis",seckill.getSeckillId(),seckill.getKillCount());
            redisTemplate.boundValueOps("seckill"+seckill.getSeckillId()+":count").increment(seckill.getKillCount());
            //设置秒杀任务过期
            redisTemplate.boundValueOps("seckill"+seckill.getSeckillId()+":count").expireAt(seckill.getEndTime());
            /**
             * 修改数据库中的秒杀对象状态
             */
            seckillRepository.updateStatus(1,seckill.getSeckillId());
        }

    }


}
